package com.zhongxi.guoyuan.view.seller;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.seller.SellerBeautifulAdapter;
import com.zhongxi.guoyuan.adapter.beautifulStoreOrder.BillAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.BaseResult;
import com.zhongxi.guoyuan.entity.seller.BillData;
import com.zhongxi.guoyuan.entity.seller.BillResult;
import com.zhongxi.guoyuan.entity.seller.InnerInfoResult;
import com.zhongxi.guoyuan.entity.seller.SellerBeautifulOrderData;
import com.zhongxi.guoyuan.entity.seller.SellerOrderInfoResult;
import com.zhongxi.guoyuan.entity.seller.SummaryResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SellerBeautifulStoreOrderActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, MyScrollView.OnScrollListener {

    private TextView tvOrder;
    private TextView tvEndTime;
    private TextView tvStartTime;
    private DatePickerDialog dialog;
    private LinearLayout linearTitle;
    private LinearLayout linearBill;
    private TextView tvBill;
    private NoScrollListView lvList;
    private List<BillData> data = new ArrayList<BillData>();
    private List<SellerBeautifulOrderData> orderData = new ArrayList<>();
    private String type;
    private Map<String, String> map = new HashMap<>();
    private String endTime;
    private String startTime;
    private int inflag = 0;
    private EditText etOrderId;
    private RadioButton rb1;
    private RadioButton rb2;
    private RadioButton rb0;
    private TextView tvPhone;
    private TextView tvAllCash;
  //  private TextView tvAllInner;
    private TextView tvReward;
    private TextView tvAllGoOrder;
    private TextView tvAllHomeOrder;
    private TextView tvQueryAllOrder;
    private TextView tvQueryAllGoStore;
    private TextView tvAllGoHome;
    private TextView tvStore;
    private TextView tvAllOrder;
    private TextView tvTips;
    private int status = 1;
    private TextView tvQuery;
    private boolean flag ;
    private SellerBeautifulAdapter adapter;
    private Spinner sp;
    private String stype = "0";
    private boolean fitst = true;
    private int pos;
    private MyScrollView myScrollView;
    private BillAdapter billAdapter;

    private boolean scroll;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    type = "confirm";
                    map.clear();
                    map.put("orderid", orderData.get(((int)msg.obj)).getId());
                    map.put("sid", orderData.get(((int)msg.obj)).getSid());
                    Log.i("base", "map:"+map.toString());
                    getServer(Url.INNER_CONFIRM_ORDER, map, "", true, null, "post");
                    break;
                case 1:
                    type = "operate";
                    map.clear();
                    map.put("orderid", orderData.get(((int)msg.obj)).getId());
                    map.put("sid", orderData.get(((int)msg.obj)).getSid());
                    Log.i("base", "map:"+map.toString());
                    getServer(Url.INNER_OPTORDER, map, "", true, null, "post");
                    break;
            }
        }
    };
    private int index;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_seller_beautiful_store_order);
        initTitle();
        tvTitle.setText("美容院总部");

        index = getIntent().getIntExtra("index", 0);

        myScrollView = (MyScrollView) findViewById(R.id.myScrollView);
        tvStartTime = (TextView) findViewById(R.id.tvStartTime);
        tvEndTime = (TextView) findViewById(R.id.tvEndTime);
        sp = (Spinner) findViewById(R.id.sp);
        tvBill = (TextView) findViewById(R.id.tvBill);
        tvOrder = (TextView) findViewById(R.id.tvOrder);
        tvOrder.setSelected(true);

        linearTitle = (LinearLayout) findViewById(R.id.linearTitle);
        linearBill = (LinearLayout) findViewById(R.id.linearBill);
        lvList = (NoScrollListView) findViewById(R.id.lvList);
        etOrderId = (EditText) findViewById(R.id.etOrderId);
        tvTips = (TextView) findViewById(R.id.tvTips);
        tvQuery = (TextView) findViewById(R.id.tvQuery);

        rb0 = (RadioButton) findViewById(R.id.rb0);
        rb1 = (RadioButton) findViewById(R.id.rb1);
        rb2 = (RadioButton) findViewById(R.id.rb2);

        tvStore = (TextView) findViewById(R.id.tvStore);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvAllCash = (TextView) findViewById(R.id.tvAllCash);
      //  tvAllInner = (TextView) findViewById(R.id.tvAllInner);
        tvReward = (TextView) findViewById(R.id.tvReward);
        tvAllOrder = (TextView) findViewById(R.id.tvAllOrder);
        tvAllGoOrder = (TextView) findViewById(R.id.tvAllGoOrder);
        tvAllHomeOrder = (TextView) findViewById(R.id.tvAllHomeOrder);
        tvQueryAllOrder = (TextView) findViewById(R.id.tvQueryAllOrder);
        tvQueryAllGoStore = (TextView) findViewById(R.id.tvQueryAllGoStore);
        tvAllGoHome = (TextView) findViewById(R.id.tvAllGoHome);
    }

    /**
     * 初始化数据
     * @param result
     */
    private void initInfo(InnerInfoResult result) {
        if(null!=result.getConsole()&&!"".equals(result.getConsole())){
            InnerInfoResult.ConsoleCoinRecordDetailResult console = result.getConsole();
            if(null!=console.getName()&&!"".equals(console.getName())){
                tvStore.setText(console.getName());
            }else{
                tvStore.setText("");
            }
            if(null!=console.getMphone()&&!"".equals(console.getMphone())){
                tvPhone.setText("电话："+console.getMphone());
            }else{
                tvPhone.setText("电话：");
            }
        }
        if(null!=result.getStatistics()&&!"".equals(result.getStatistics())){
            InnerInfoResult.StatisticsCoinRecordDetailResult statistics = result.getStatistics();
            if(null!=statistics.getOrderNum()&&!"".equals(statistics.getOrderNum())){
                tvAllOrder.setText(statistics.getOrderNum());
            }else{
                tvAllOrder.setText("");
            }
            if(null!=statistics.getOrderNumToDoor()&&!"".equals(statistics.getOrderNumToDoor())){
                tvAllHomeOrder.setText(statistics.getOrderNumToDoor());
            }else{
                tvAllHomeOrder.setText("");
            }
            if(null!=statistics.getOrderNumToShop()&&!"".equals(statistics.getOrderNumToShop())){
                tvAllGoOrder.setText(statistics.getOrderNumToShop());
            }else{
                tvAllGoOrder.setText(statistics.getOrderNumToShop());
            }
            if(null!=statistics.getData()&&!"".equals(statistics.getData())){
                InnerInfoResult.StatisticsCoinRecordDetailResult.DataCoinRecordDetailResult info = statistics.getData();
                if(null!=info.getPay()&&!"".equals(info.getPay())){
                    tvAllCash.setText("总现金收入："+info.getPay()+"元");
                }else{
                    tvAllCash.setText("总现金收入*元");
                }
//                if(null!=info.getPayinnerprice()&&!"".equals(info.getPayinnerprice())){
//                    tvAllInner.setText("总美币收入："+info.getPayinnerprice()+"美币");
//                }else{
//                    tvAllInner.setText("总美币收入*美币");
//                }
                if(null!=info.getBacksilvernum()&&!"".equals(info.getBacksilvernum())){
                    tvReward.setText("总返银支出："+info.getBacksilvernum()+"银币");
                }else{
                    tvReward.setText("总返银支出：*银币");
                }
            }
        }
    }

    private void initOrderInfo(SummaryResult.StatisticsCoinRecordDetailResult result) {
        if(null!=result.getOrderNum()&&!"".equals(result.getOrderNum())){
            tvQueryAllOrder.setText("下单数量："+result.getOrderNum()+"单");
        }else{
            tvQueryAllOrder.setText("下单数量：*单");
        }
        if(null!=result.getOrderNumToShop()&&!"".equals(result.getOrderNumToShop())){
            tvQueryAllGoStore.setText("到店订单："+result.getOrderNumToShop()+"单");
        }else{
            tvQueryAllGoStore.setText("到店订单：*单");
        }
        if(null!=result.getOrderNumToDoor()&&!"".equals(result.getOrderNumToDoor())){
            tvAllGoHome.setText("上门订单："+result.getOrderNumToDoor()+"单");
        }else{
            tvAllGoHome.setText("上门订单：*单");
        }
    }

    @Override
    protected void initData() {
        super.initData();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(now);
        tvStartTime.setText(dateNowStr);
        tvEndTime.setText(dateNowStr);
        startTime = endTime = dateNowStr;

        if(inflag == 0){
            adapter = new SellerBeautifulAdapter(context, orderData, handler);
            lvList.setAdapter(adapter);
        }else if(inflag == 1){
            billAdapter = new BillAdapter(context, data);
            lvList.setAdapter(billAdapter);
        }

        type = "info";
        getServer(Url.INNER_INFO, null, "", true, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        myScrollView.setOnScrollListener(this);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);
        tvBill.setOnClickListener(this);
        tvOrder.setOnClickListener(this);
        rb0.setOnClickListener(this);
        rb1.setOnClickListener(this);
        rb2.setOnClickListener(this);
        tvQuery.setOnClickListener(this);
        lvList.setOnItemClickListener(this);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    stype = "0";
                }else if(position==1){
                    stype = "1";
                }else if(position ==2){
                    stype = "2";
                }
                if(!fitst){
                    pageNum = 1;
                    getOrder();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

//    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvStartTime:
                showDateDialog(0);
                break;
            case R.id.tvEndTime:
                showDateDialog(1);
                break;
            case R.id.tvBill:
                inflag = 1;
                pageNum = 1;
                tvBill.setSelected(true);
                tvOrder.setSelected(false);
                tvTips.setText("订单号：");
                linearTitle.setVisibility(View.GONE);
                linearBill.setVisibility(View.VISIBLE);
                billAdapter = new BillAdapter(context, data);
                lvList.setAdapter(billAdapter);
                getBillData();
                break;
            case R.id.tvOrder:
                inflag = 0;
                pageNum = 1;
                tvOrder.setSelected(true);
                tvBill.setSelected(false);
                tvTips.setText("手机号：");
                linearTitle.setVisibility(View.VISIBLE);
                linearBill.setVisibility(View.GONE);
                adapter = new SellerBeautifulAdapter(context, orderData, handler);
                lvList.setAdapter(adapter);
                getOrder();
                break;
            case R.id.rb0:
                rb0.setChecked(true);
                rb1.setChecked(false);
                rb2.setChecked(false);
                status = 1;
                pageNum = 1;
                getOrder();
                break;
            case R.id.rb1:
                rb0.setChecked(false);
                rb1.setChecked(true);
                rb2.setChecked(false);
                status = 2;
                pageNum = 1;
                getOrder();
                break;
            case R.id.rb2:
                rb0.setChecked(false);
                rb1.setChecked(false);
                rb2.setChecked(true);
                status = 3;
                pageNum = 1;
                getOrder();
                break;
            case R.id.tvQuery:
                pageNum = 1;
                getOrder();
                break;
        }
    }

    /**
     * 获取细账
     */
    private void getBillData() {
        if(CommonTool.TimeCompare(startTime, endTime)){
            type = "bill";
            map.clear();
            map.put("stime", startTime);
            map.put("etime", endTime);
            map.put("orderid", etOrderId.getText().toString().trim());
            String str = "&page="+pageNum;
            scroll = false;
            getServer(Url.INNER_ORDER_DETAILS, map, str, true, null, "post");
        }else {
            showShortToast("结束时间不能小于开始时间");
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("info".equals(type)){
                InnerInfoResult result = gson.fromJson(response, InnerInfoResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                fitst = false;
                getOrder();
                initInfo(result);
            }else if("bill".equals(type)){
                BillResult result = gson.fromJson(response, BillResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(pageNum ==1){
                    data.clear();
                }
                if(null!=result.getData()&&result.getData().size()>0){
                    data.addAll(result.getData());
                }
                scroll = true;
                billAdapter.notifyDataSetChanged();
            }else if("queryInfo".equals(type)){
                SummaryResult result = gson.fromJson(response, SummaryResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(null!=result.getStatistics()&&!"".equals(result.getStatistics())){
                    initOrderInfo(result.getStatistics());
                }
                flag = true;
            }else if("order".equals(type)){
                JSONObject obj = new JSONObject(response);
                JSONArray ary = obj.getJSONArray("data");
                JSONObject baseObj = obj.getJSONObject("safeobj");
                List<SellerBeautifulOrderData> listData = SellerBeautifulOrderData.parseMatch(ary);
                BaseResult baseResult = BaseResult.parseMatch(baseObj);
                MyApplication.getInstance().setSpValue(baseResult);
                if(pageNum == 1){
                    orderData.clear();
                }
                if(listData.size()>0){
                    orderData.addAll(listData);
                }
                adapter.setJSONObject(obj);
                adapter.setType(status);
                adapter.setmExpandedMenuPos(-1, null);
                adapter.notifyDataSetChanged();
                scroll = true;
                /*if(pageNum == 1&& orderData.size()==0){
                    adapter.notifyDataSetChanged();
                }*/
                if(!flag){
                    getQueryInfo();
                }
            }else if("orderinfo".equals(type)){
                SellerOrderInfoResult infoResult = gson.fromJson(response, SellerOrderInfoResult.class);
                MyApplication.getInstance().setSpValue(infoResult.getSafeobj());
                if (pos == adapter.getmExpandedMenuPos()) {
                    adapter.setmExpandedMenuPos(-1, infoResult);
                } else {
                    adapter.setmExpandedMenuPos(pos, infoResult);
                }
                adapter.notifyDataSetChanged();
            }else if("confirm".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showShortToast("确认订单成功");
                adapter.notifyDataSetChanged();
                getOrder();
            }else if("operate".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                adapter.notifyDataSetChanged();
                showShortToast("操作订单成功");
                getOrder();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        if(result.getCode()==9002){
            showShortToast("登录已失效，请重新登录");
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            sharedPrefrences.edit().putString("beautifulcredentials", "").commit();
            startAct(SellerBeautifulStoreLoginActivity.class);
            finish();
        }else if(result.getCode() == 6202){
            showShortToast("您预约的项目已下架");
        }else if(result.getCode() == 6201){
            showShortToast("您预约的店铺已关闭，建议您取消该订单后重新选择");
        }else if (result.getCode() == 6203){
            showShortToast("您预约的服务已下架");
        }
    }

    /**
     * 查询某个时间内的订单数
     */
    private void getQueryInfo() {
        if(CommonTool.TimeCompare(startTime, endTime)){
            type = "queryInfo";
            map.clear();
            map.put("stime", startTime);
            map.put("etime", endTime);
            getServer(Url.INNER_ORDER_SUMMARY, map, "", true, null, "post");
        }else {
            showShortToast("结束时间不能小于开始时间");
        }
    }

    /**
     * 获取
     */
    private void getOrder() {
        type = "order";
        map.clear();
        map.put("userphone", etOrderId.getText().toString().trim());
        map.put("sType", stype);
        map.put("status", status+"");
        String str = "&page="+pageNum;
        Log.i("base", "map:"+map.toString());
        scroll = false;
        getServer(Url.INNER_ORDER_STATUS, map, str, true, null, "post");
    }

//    @RequiresApi(api = Build.VERSION_CODES.N)
    private void showDateDialog(final int index) {
        Calendar c = Calendar.getInstance();
        dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String mon = month + 1 +"";
                String text = year + "-" + mon + "-" + dayOfMonth;
                if(index == 0){
                    tvStartTime.setText(text);
                    startTime = text;
                }else if(index == 1){
                    tvEndTime.setText(text);
                    endTime = text;
                }
                flag = true;
                pageNum = 1;
                if(inflag == 0){
                    getQueryInfo();
                }else if(inflag == 1){
                    getBillData();
                }
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.setTitle("请选择时间：");
        dialog.getDatePicker().setCalendarViewShown(false);
        dialog.show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(inflag == 0){
            pos = position;
            type = "orderinfo";
            String str = "&orderid="+orderData.get(position).getId()+"&sid="+orderData.get(position).getSid()+"&ssid="+orderData.get(position).getSsid()+"&sstype="+orderData.get(position).getSstype();
            Log.i("base", str);
            getServer(Url.INNER_SUBSCRIBE_INFO, null, str, true, null, "get");
        }
    }

    @Override
    public void onScroll(int scrollY) {

    }

    @Override
    public void scrollBottom() {
        if(!MyTextUtils.isFastDoubleClick()&&scroll&&adapter.getmExpandedMenuPos()==-1){
            pageNum ++;
            if(inflag == 1){
                getBillData();
            }else if(inflag == 0){
                getOrder();
            }
        }
    }
}
